package dao

import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import play.api.libs.json.JsValue
import slick.jdbc.JdbcProfile
import tool.Pojo.{PageData, RegionData}

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global


/**
 * Created by yz on 2019/1/9
 */
class BasicDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import profile.api._

  type MyRow = BasicRow
  val table = Basic

  def insertAll(rows: Seq[MyRow]) = {
    db.run(table ++= rows).map(_ => ())
  }

  def deleteAll = db.run(table.delete).map(_ => ())

  def selectAll = db.run(table.result)

  def selectAllChrs(species: String) = db.run(table.filter(_.species === species).map(_.chr).
    distinct.result)

  def selectAll(geneIds: Seq[String]) = db.run(table.filter(_.id.
    inSetBind(geneIds)).result)

  def selectByGeneIds(geneIds: Seq[String]) = db.
    run(table.filter(_.id.inSetBind(geneIds)).result)

  def selectByGeneIds(geneIds: Seq[String], species: String) = db.
    run(table.filter(_.species === species).filter(_.id.inSetBind(geneIds)).result)

  def selectByGeneId(geneId: String) = db.run(Basic.join(Cds).on(_.id === _.geneId).
    join(Pep).on(_._1.id === _.geneId).map(x => (x._1._1, x._1._2, x._2)).filter(_._1.id === geneId).result.head)

  def selectBasicByGeneId(geneId: String) = db.run(table.filter(_.id === geneId).
    result.head)

  def selectAllGeneIds = db.run(table.map(_.id).result)

  def selectByGeneNames(geneNames: Seq[String], species: String) = db.
    run(Basic.filter(_.species === species).filter(_.geneName.inSetBind(geneNames)).result)

  def selectAllGeneNames = db.run(table.map(_.geneName).result)

  def selectByRegionData(data: RegionData) = db.run(table.filter(_.chr === data.chr)
    .filter(_.start >= data.start).filter(_.end <= data.end).result)

}
